﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.ServiceModel;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.ServiceModel.Security.Tokens;
using Sinacor.Infra.Common.Security.Authentication.Credentials;

namespace Sinacor.Infra.Common.Security.Authentication.ClientCredentials
{
    internal class SinacorClientCredentialsSecurityTokenManager : ClientCredentialsSecurityTokenManager
    {
        SinacorClientCredentials credentials;

        public SinacorClientCredentialsSecurityTokenManager (SinacorClientCredentials credentials)
            : base(credentials)
        {
            this.credentials = credentials;
        }

        public override SecurityTokenProvider CreateSecurityTokenProvider(
            SecurityTokenRequirement tokenRequirement)
        {
            // Verifica se o Tipo do Token é um SinacorToken
            if (tokenRequirement.TokenType == Constants.SinacorTokenType)
                return new SinacorTokenProvider(credentials.UserInfo);

            //Verifica se a requisição é para um IssuedToken
            if (IsIssuedSecurityTokenRequirement(tokenRequirement))
            {
                return new CachedIssuedSecurityTokenProvider((IssuedSecurityTokenProvider)base.CreateSecurityTokenProvider(tokenRequirement), this.credentials.UserInfo.TokenId);
            }

            else if (tokenRequirement is InitiatorServiceModelSecurityTokenRequirement)
            {
                if (tokenRequirement.TokenType == SecurityTokenTypes.X509Certificate)
                {
                    return new X509SecurityTokenProvider(credentials.ServiceCertificate.DefaultCertificate);
                }
            }

            return base.CreateSecurityTokenProvider(tokenRequirement);
        }

        /// <summary>
        /// Cria uma instância de um <see cref="SinacorTokenSerializer"/>.
        /// </summary>
        /// <param name="version"></param>
        /// <returns></returns>
        public override SecurityTokenSerializer CreateSecurityTokenSerializer(SecurityTokenVersion version)
        {
            return new SinacorTokenSerializer(version);
        }
    }

}
